package com.tian.util;

import java.text.DecimalFormat;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年09月20日 15:03
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 *
 * 贷款10万，年利率4.8，等额本金还款方式，12期还完，生成12期还款计划
 */
public class LoanCalculator {
    /*public static void main(String[] args) {
        double loanAmount = 100000; // 贷款金额
        double annualInterestRate = 4.8; // 年利率
        int numberOfPayments = 12; // 还款期数

        double monthlyInterestRate = annualInterestRate / 100 / 12; // 月利率
        double monthlyPayment = loanAmount / numberOfPayments; // 每月还款本金

        System.out.println("还款计划：");
        System.out.println("期数\t本金\t利息\t总额");

        for (int i = 1; i <= numberOfPayments; i++) {
            double interest = loanAmount * monthlyInterestRate * (numberOfPayments - i + 1) / numberOfPayments; // 当期利息
            double totalPayment = monthlyPayment + interest; // 当期总额
            System.out.printf("%d\t%.2f\t%.2f\t%.2f\n", i, monthlyPayment, interest, totalPayment);
        }
    }*/
    public static void main(String[] args) {
        double loanAmount = 100000; // 贷款金额
        double annualInterestRate = 4.8; // 年利率
        int numberOfPayments = 12; // 还款期数

        double monthlyInterestRate = annualInterestRate / 100 / 12;
        double monthlyPayment = loanAmount * monthlyInterestRate / (1 - Math.pow(1 + monthlyInterestRate, -numberOfPayments));

        DecimalFormat df = new DecimalFormat("#.00");

        System.out.println("期数\t\t本期还款\t\t剩余贷款");

        for (int i = 1; i <= numberOfPayments; i++) {
            double interestPayment = loanAmount * monthlyInterestRate; // 本期利息
            double principalPayment = monthlyPayment - interestPayment; // 本期本金
            loanAmount -= principalPayment; // 剩余贷款

            System.out.println(i + "\t\t" + df.format(interestPayment+principalPayment) + "\t\t" + df.format(loanAmount));
        }
    }
}
